<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {
  PlusOutlined,
  HomeOutlined,
  RightOutlined,
  CheckCircleOutlined,
  UserOutlined,
  SettingOutlined,
  MoreOutlined,
  EditOutlined,
  DeleteOutlined,
  MenuUnfoldOutlined,
  AppstoreOutlined,
  StarOutlined,
  FolderOutlined,
} from '@ant-design/icons-vue';
import { Card, Button, message, Empty, Spin, Dropdown, Modal } from 'ant-design-vue';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { $t } from '#/locales';
import { useTableForgeStore } from '#/store/tableforge';
import { deleteApp } from '#/api/core/app';
import AppDrawer from './app-drawer.vue';
import { useAccessStore } from '@vben/stores';
import { DEFAULT_HOME_PATH } from '@vben/constants';
import { useAuthStore } from '#/store/auth';
import { getAppRouters } from '#/api/core/menu';

defineOptions({ name: 'ApplicationSelector' });

const router = useRouter();
const tableForgeStore = useTableForgeStore();
const accessStore = useAccessStore();
const authStore = useAuthStore();

const [AppDrawerComponent, drawerApi] = useVbenDrawer({
  connectedComponent: AppDrawer,
});

interface Application {
  id: string;
  name: string;
  icon: string;
  color: string;
  description?: string;
}

const applications = ref<Application[]>([]);
const loading = ref(true);
const showDrawer = ref(false);

// 获取应用列表
async function fetchApplications() {
  try {
    loading.value = true;

    // 先获取空间列表
    const spaces = await tableForgeStore.fetchSpaceList();
    if (spaces && spaces.length > 0) {
      // 默认使用第一个空间
      const spaceId = spaces[1]?.id;
      if (spaceId) {
        tableForgeStore.setCurrentSpace(spaceId);

        // 获取该空间下的应用列表
        const appList = await tableForgeStore.fetchAppList(spaceId);

        // 将API返回的应用转换为界面需要的格式
        applications.value = appList.map(app => ({
          id: app.id,
          name: app.name,
          description: app.description || '',
          // 根据应用图标字段设置，如果没有则使用默认值
          icon: getIconName(app.icon || 'home'),
          // 随机生成颜色或使用默认颜色
          color: getColorByIcon(app.icon || 'home')
        }));
      }
    }
    loading.value = false;
  } catch (error) {
    console.error('获取应用列表失败', error);
    message.error('获取应用列表失败');
    loading.value = false;
  }
}

onMounted(async () => {
  // 从API获取应用列表
  await fetchApplications();
});

// 根据图标名称返回对应的颜色
function getColorByIcon(icon: string): string {
  const colorMap: Record<string, string> = {
    'home': '#1abc9c',
    'user': '#9b59b6',
    'setting': '#e74c3c',
    'check-circle': '#3498db',
    'arrow-right': '#f1c40f'
  };

  return colorMap[icon] || '#1890ff';
}

// 转换图标名称为前端可识别的名称
function getIconName(icon: string): string {
  // 这里可以根据后端返回的图标字段做映射
  const iconMap: Record<string, string> = {
    'home-icon': 'home',
    'user-icon': 'user',
    'settings-icon': 'setting',
    'check-icon': 'check-circle',
    'arrow-icon': 'arrow-right'
  };

  return iconMap[icon] || icon || 'home';
}

const handleSelectApp = async (app: Application) => {
  try {
    // 1. 显示加载提示
    message.loading('正在加载应用...', 0);

    // 2. 保存应用信息
    localStorage.setItem('currentAppId', app.id);
    localStorage.setItem('currentAppName', app.name);
    tableForgeStore.setCurrentApp(app.id);

    // 3. 重新获取用户权限
    const { userInfo } = await authStore.fetchUserInfo();
    if (userInfo?.permissions) {
      accessStore.setAccessCodes(userInfo.permissions);
    }

    // 4. 获取应用特定的路由
    const menus = await getAppRouters(app.id);
    if (menus) {
      // 设置应用的路由菜单
      accessStore.setAccessMenus(menus);
    }

    // 5. 提示成功并跳转
    message.destroy();
    message.success(`已进入应用: ${app.name}`);
    router.push(DEFAULT_HOME_PATH);
  } catch (error) {
    message.destroy();
    message.error('加载应用失败，请重试');
    console.error('加载应用失败:', error);
  }
};

const handleCreateApp = () => {
  // 打开抽屉而不是跳转
  showDrawer.value = true;
};

// 获取图标组件
const getIconComponent = (iconName: string) => {
  switch (iconName) {
    case 'home':
      return HomeOutlined;
    case 'arrow-right':
      return RightOutlined;
    case 'check-circle':
      return CheckCircleOutlined;
    case 'user':
      return UserOutlined;
    case 'setting':
      return SettingOutlined;
    default:
      return HomeOutlined;
  }
};

// 应用创建成功后刷新列表
const handleAppCreated = () => {
  fetchApplications();
};

function handleAdd() {
  drawerApi.open();
}

// 添加删除应用的方法
const handleDeleteApp = async (app: Application, e: MouseEvent) => {
  e.stopPropagation(); // 阻止事件冒泡
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除应用"${app.name}"吗？`,
    okType: 'danger',
    async onOk() {
      try {
        await deleteApp(app.id);
        message.success('删除成功');
        await fetchApplications();
      } catch (error) {
        console.error('删除应用失败', error);
        message.error('删除应用失败');
      }
    },
  });
};

// 添加编辑应用的方法
const handleEditApp = (app: Application, e: MouseEvent) => {
  e.stopPropagation(); // 阻止事件冒泡
  drawerApi.setData(app);
  drawerApi.open();
};
</script>

<template>
  <Page :auto-content-height="true">
    <div class="page-container">
      <!-- 左侧导航 -->
      <div class="side-nav">
        <div class="nav-header">
          <h3>应用</h3>
          <Button type="text">
            <MenuUnfoldOutlined />
          </Button>
        </div>

        <!-- 快捷导航 -->
        <div class="quick-nav">
          <div class="nav-item active">
            <AppstoreOutlined />
            <span>全部</span>
          </div>
          <div class="nav-item">
            <StarOutlined />
            <span>我拥有的</span>
          </div>
          <div class="nav-item">
            <DeleteOutlined />
            <span>回收站</span>
          </div>
        </div>

        <!-- 分组列表 -->
        <div class="group-section">
          <div class="section-header">
            <span>分组</span>
            <Button type="text" class="add-btn">
              <PlusOutlined />
            </Button>
          </div>
          <div class="group-list">
            <div class="group-item">
              <FolderOutlined />
              <span>标准应用</span>
              <span class="count">2</span>
            </div>
            <div class="group-item">
              <FolderOutlined />
              <span>售前POC</span>
              <span class="count">6</span>
            </div>
            <div class="group-item active">
              <FolderOutlined />
              <span>组织测试</span>
              <span class="count">4</span>
            </div>
            <div class="group-item">
              <FolderOutlined />
              <span>内部应用</span>
              <span class="count">6</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容区 -->
      <div class="main-content">
        <div class="application-container">
          <div class="application-selector">
            <div class="app-header">
              <h1>{{ $t('application.selectApp') }}</h1>
              <p class="app-header-desc">
                {{ $t('application.selectAppDesc') }}
              </p>
            </div>

            <Spin :spinning="loading">
              <div class="app-grid">
                <template v-if="applications.length > 0">
                  <Card
                    v-for="app in applications"
                    :key="app.id"
                    class="app-card"
                    :body-style="{ padding: '0' }"
                    :bordered="false"
                    hoverable
                    @click="handleSelectApp(app)"
                  >
                    <div class="app-actions">
                      <Dropdown trigger="click" @click.stop>
                        <Button type="text" class="action-btn" @click.stop>
                          <MoreOutlined />
                        </Button>
                        <template #overlay>
                          <a-menu class="action-menu">
                            <a-menu-item @click="(e: MouseEvent) => handleEditApp(app, e)">
                              <EditOutlined />
                              <span>修改</span>
                            </a-menu-item>
                            <a-menu-item @click="(e: MouseEvent) => handleDeleteApp(app, e)">
                              <DeleteOutlined />
                              <span>删除</span>
                            </a-menu-item>
                          </a-menu>
                        </template>
                      </Dropdown>
                    </div>
                    <div class="app-content">
                      <div class="app-icon" :style="{ backgroundColor: app.color }">
                        <component :is="getIconComponent(app.icon)" />
                      </div>
                      <div class="app-info">
                        <div class="app-name">{{ app.name }}</div>
                        <div v-if="app.description" class="app-description">{{ app.description }}</div>
                      </div>
                    </div>
                  </Card>
                </template>

                <Empty v-else description="暂无应用" />

                <Card class="app-card add-card" :bordered="false" hoverable @click="handleAdd">
                  <div class="app-content">
                    <div class="add-icon">
                      <PlusOutlined />
                    </div>
                    <div class="app-info">
                      <div class="app-name">新建应用</div>
                      <div class="app-description">点击创建一个新的应用</div>
                    </div>
                  </div>
                </Card>
              </div>
            </Spin>
          </div>
        </div>
      </div>
    </div>
    <AppDrawerComponent @reload="handleAppCreated" />
  </Page>
</template>

<style lang="scss" scoped>
.page-container {
  display: flex;
  height: 100%;
  background: #fafbfc;
  padding: 12px;
}

.side-nav {
  width: 200px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  margin-right: 12px;
  overflow: hidden;

  .nav-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
    border-bottom: 1px solid #f0f2f5;

    h3 {
      font-size: 14px;
      font-weight: 500;
      color: #333;
      margin: 0;
    }
  }

  .quick-nav {
    padding: 6px;

    .nav-item {
      display: flex;
      align-items: center;
      padding: 8px 10px;
      color: #666;
      font-size: 13px;
      cursor: pointer;
      border-radius: 4px;
      margin: 1px 0;
      transition: all 0.15s ease;

      .anticon {
        margin-right: 8px;
        font-size: 14px;
      }

      &:hover {
        color: #4096ff;
        background: #f0f7ff;
      }

      &.active {
        color: #4096ff;
        background: #f0f7ff;
        font-weight: 500;
      }
    }
  }

  .group-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 6px;
    margin-top: 2px;
    border-top: 1px solid #f0f2f5;

    .section-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 10px 6px;
      color: #999;
      font-size: 12px;

      .add-btn {
        padding: 2px;
        color: #999;

        &:hover {
          color: #4096ff;
        }
      }
    }

    .group-list {
      flex: 1;
      overflow-y: auto;

      .group-item {
        display: flex;
        align-items: center;
        padding: 8px 10px;
        color: #666;
        font-size: 13px;
        cursor: pointer;
        border-radius: 4px;
        margin: 1px 0;
        transition: all 0.15s ease;

        .anticon {
          margin-right: 8px;
          font-size: 14px;
          color: #999;
        }

        .count {
          margin-left: auto;
          font-size: 11px;
          color: #999;
          background: #f5f5f5;
          padding: 1px 6px;
          border-radius: 10px;
        }

        &:hover {
          color: #4096ff;
          background: #f0f7ff;

          .anticon {
            color: #4096ff;
          }

          .count {
            color: #4096ff;
            background: #f0f7ff;
          }
        }

        &.active {
          color: #4096ff;
          background: #f0f7ff;

          .anticon {
            color: #4096ff;
          }

          .count {
            color: #4096ff;
            background: #e6f4ff;
          }
        }
      }
    }
  }
}

.main-content {
  flex: 1;
  min-width: 0;
}

.application-container {
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
  padding: 20px;
}

.application-selector {
  max-width: 1200px;
  margin: 0 auto;
}

.app-header {
  text-align: center;
  margin-bottom: 24px;

  h1 {
    font-size: 20px;
    font-weight: 500;
    color: #333;
    margin-bottom: 6px;
  }

  .app-header-desc {
    font-size: 13px;
    color: #999;
    max-width: 500px;
    margin: 0 auto;
  }
}

.app-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 12px;
  margin: 0 auto;
}

.app-card {
  height: 90px;
  transition: all 0.15s ease;
  cursor: pointer;
  border-radius: 6px;
  background: #fff;
  position: relative;
  overflow: hidden;
  border: 1px solid #f0f0f0;

  &:hover {
    border-color: #4096ff;
    box-shadow: 0 2px 8px rgba(64, 150, 255, 0.08);
    transform: translateY(-1px);

    .app-icon {
      transform: scale(1.05);
    }

    .action-btn {
      opacity: 1;
    }
  }

  .app-content {
    display: flex;
    align-items: center;
    padding: 14px;
    height: 100%;
  }

  .app-icon {
    width: 36px;
    height: 36px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: white;
    transition: all 0.15s ease;
    flex-shrink: 0;
    background: linear-gradient(135deg, #4096ff, #1677ff);
    box-shadow: 0 2px 6px rgba(64, 150, 255, 0.15);
  }

  .app-info {
    margin-left: 12px;
    flex: 1;
    min-width: 0;
  }

  .app-name {
    font-size: 13px;
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .app-description {
    font-size: 12px;
    color: #999;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    line-height: 1.4;
  }
}

.add-card {
  background: #fafafa;
  border: 1px dashed #e8e8e8;

  &:hover {
    background: #f0f7ff;
    border-color: #4096ff;

    .add-icon {
      background: linear-gradient(135deg, #4096ff, #1677ff);
      color: white;
      transform: scale(1.05);
    }

    .app-name {
      color: #4096ff;
    }
  }

  .add-icon {
    width: 36px;
    height: 36px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    background: #f5f5f5;
    color: #999;
    transition: all 0.15s ease;
  }

  .app-name {
    color: #666;
  }

  .app-description {
    color: #999;
  }
}

.app-actions {
  position: absolute;
  top: 6px;
  right: 6px;
  z-index: 1;
}

.action-btn {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
  opacity: 0;
  transition: all 0.15s ease;
  background: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  &:hover {
    color: #4096ff;
    background: #f0f7ff;
  }
}

:deep(.action-menu) {
  min-width: 100px;
  border-radius: 6px;
  padding: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;

  .ant-dropdown-menu-item {
    border-radius: 4px;
    padding: 6px 10px;
    color: #666;
    font-size: 13px;

    &:hover {
      color: #4096ff;
      background: #f0f7ff;
    }

    .anticon {
      margin-right: 6px;
      font-size: 14px;
    }
  }
}

:deep(.ant-empty) {
  grid-column: 1 / -1;
  padding: 32px 0;
  color: #999;

  .ant-empty-image {
    opacity: 0.4;
    transform: scale(0.8);
  }
}
</style>
